package com.ec50n9.server.module.comment

import cn.dev33.satoken.stp.StpUtil
import com.ec50n9.server.common.SpringUtils
import com.ec50n9.server.module.common.CreateForm
import com.ec50n9.server.module.common.Render
import com.ec50n9.server.module.common.Rendered
import com.ec50n9.server.module.common.renderTo
import com.ec50n9.server.module.issue.IssueService
import com.ec50n9.server.module.user.User
import com.ec50n9.server.module.user.UserQueryRendered
import com.ec50n9.server.module.user.UserService
import org.hibernate.annotations.GenericGenerator
import java.time.LocalDateTime
import javax.persistence.*
import javax.validation.constraints.NotBlank

@Entity
class Comment(
    var content: String,

    @ManyToOne
    var author: User,

    var createdTime: LocalDateTime = LocalDateTime.now(),

    @Id
    @GenericGenerator(name = "nanoid", strategy = "com.ec50n9.server.common.NanoIdGenerator")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "nanoid")
    var id: String? = null
) : Render<Comment>()

data class CommentCreateForm(
    @field:NotBlank(message = "评论内容不能为空")
    var content: String?,
    var issueId: String?
) : CreateForm<Comment> {
    override fun renderTo(): Comment {
        val userService = SpringUtils.getBean(UserService::class.java)
        val issueService = SpringUtils.getBean(IssueService::class.java)

        val user = userService.findOneByUsername(StpUtil.getLoginId() as String)
        return Comment(content!!, user)
    }
}

data class CommentListRendered(
    var id: String? = null,
    var content: String? = null,
    var authorName: String? = null,
    var createdTime: LocalDateTime? = null
) : Rendered<Comment> {
    override fun renderFrom(from: Comment) {
        id = from.id
        content = from.content
        authorName = from.author.nickname
        createdTime = from.createdTime
    }
}

data class CommentDetailRendered(
    var id: String? = null,
    var content: String? = null,
    var author: UserQueryRendered? = null,
    var createdTime: LocalDateTime? = null
) : Rendered<Comment> {
    override fun renderFrom(from: Comment) {
        id = from.id
        content = from.content
        author = from.author.renderTo(UserQueryRendered::class.java)
        createdTime = from.createdTime
    }
}
